﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace KD.Service.HR.Utility
{
    public static class Utilities
    {
        /// <summary>
        /// Copy fields of source object to the target object, if match.
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="src"></param>
        public static void ShallowCopy(object dest, object src)
        {
            var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
            var dt = dest.GetType();
            var st = src.GetType();
            var destFields = dt.GetFields(flags).Concat(dt.BaseType.GetFields(flags)).ToArray();
            var srcFields = st.GetFields(flags).Concat(st.BaseType.GetFields(flags)).ToArray();

            foreach (var srcField in srcFields)
            {
                var destField = destFields.FirstOrDefault(field => field.Name == srcField.Name);

                if (destField != null && !destField.IsLiteral)
                {
                    if (srcField.FieldType == destField.FieldType)
                    {
                        destField.SetValue(dest, srcField.GetValue(src));
                    }
                }
            }
        }

        public static List<NameValuePair> GetNameValuePairs(Type enumType)
        {
            var pairs = new List<NameValuePair>();
            var values = Enum.GetValues(enumType);
            foreach (var value in values)
            {
                var name = Enum.GetName(enumType, value);
                pairs.Add(new NameValuePair()
                {
                    Name = name,
                    Value = Convert.ToInt32(value)
                });
            }

            return pairs;
        }
    }

    public class NameValuePair
    {
        public string Name { get; set; }

        public int Value { get; set; }
    }
}
